package cn.hg.solon.youcan.framework.directive.common;

import java.util.List;
import java.util.function.Supplier;

import org.dromara.hutool.core.text.StrValidator;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

import cn.hg.solon.youcan.common.constant.CacheConstants;
import cn.hg.solon.youcan.framework.cache.YoucanCacheService;
import cn.hg.solon.youcan.framework.directive.BaseDirective;
import cn.hg.solon.youcan.system.entity.Config;
import cn.hg.solon.youcan.system.service.ConfigService;

/**
 * 获取参数列表指令：#CONFIGS('type')
 * 
 * @author 胡高
 */
@Component("view:" + ConfigsDirective.DIRECTIVE_NAME)
public class ConfigsDirective extends BaseDirective {

    public static final String DIRECTIVE_NAME = "CONFIGS";

    @Inject
    private ConfigService configService;

    @Inject
    private YoucanCacheService cacheService;

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {
        // 参数类型
        String type = this.getParaToString(0, scope);
        if (StrValidator.isBlank(type)) {
            throw new TemplateException("The parameter of #" + DIRECTIVE_NAME + " directive can not be blank",
                this.location);
        }

        List<? extends Config> list = this.cacheService.getOrStoreTag(
            CacheConstants.SYS_CONFIG_KEY + ":" + DIRECTIVE_NAME + ":" + type,
            CacheConstants.CACHE_SECONDS_ONE_DAY, new Supplier<List<? extends Config>>() {
                @Override
                public List<? extends Config> get() {
                    /*
                     * 查询字典类型列表
                     */
                    return ConfigsDirective.this.configService.listByType(type);
                }

            } , CacheConstants.SYS_CONFIG_TAG);

        scope.set(this.getPara("var", scope, DIRECTIVE_NAME.toLowerCase()), list);
    }

}
